package com.example.springboot.config.filter;


import com.alibaba.fastjson.JSON;
import com.example.springboot.utils.JwtUtil;
import com.example.springboot.vo.ResVO;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

// @WebFilter(filterName = "LoginFilter",urlPatterns = {"/*"})
// 让 LoginFilter 起作用，需要把 LoginFilter 加到 spring 中
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("--------------访问过滤器---------------------");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        Boolean isLogin = (Boolean) session.getAttribute("isLogin");
        String requestURI = request.getRequestURI();

        // 如果是登录接口，让其通过
        if (requestURI.equals("/user/login")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        if (isLogin == null) {
            // 如果不是处于登录状态，返回登录失败的数据
            ResVO<String> resVO = new ResVO<>(5002, "请登录", "");
            response.setHeader("Content-type","application/json;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(resVO));
            return;
        }
        // 如果是登录状态，让其通过
        if ((isLogin!=false)&&request.getSession().getAttribute("admin") != null) {
            filterChain.doFilter(servletRequest, servletResponse);
        }
        // new ResVO<>(2001, "请登录", "");
        else{
            String requestType = request.getHeader("X-Requested-With");
            //判断是否是ajax请求
            if(requestType!=null && "XMLHttpRequest".equals(requestType)){
                response.getWriter().write("用户未登录");
            }
            else {
                //重定向到登录页(需要在static文件夹下建立此html文件)
                // response.sendRedirect(request.getContextPath()+"/user/login");
                throw new NullPointerException();
            }
            return;
        }

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
